package com.ks.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ks.utils.RSAUtils;

@WebServlet("/generateRSAKey")
public class GenerateRSAKey extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public GenerateRSAKey() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		HashMap<String, String> keyMap = null;
		if (RSAUtils.globeStorage.containsKey(username)) {
			keyMap = RSAUtils.globeStorage.get(username);
		} else {
			keyMap = RSAUtils.createKeys(1024);
			RSAUtils.globeStorage.put(username, keyMap);
		}
		if (keyMap == null) {
			keyMap = RSAUtils.createKeys(1024);
		}

		String publicKey = keyMap.get("publicKey");
		// 将公钥传到前端
		Map<String, String> map = new HashMap<String, String>();
		// 注意返回modulus和exponent以16为基数的BigInteger的字符串表示形式
//		map.put("modulus", publicKey.getModulus().toString(16));
//		map.put("exponent", publicKey.getPublicExponent().toString(16));
		PrintWriter out = response.getWriter();
		out.print(publicKey);

	}
}
